﻿using DataVirtualization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WinDataInspector.Model;

namespace WinDataInspector.Provider
{
    class HexProvider : IItemsProvider<HexItem>
    {
        private readonly int count;
        DataInspector.DataInspector inspector;
        //private readonly int _fetchDelay;

        public HexProvider(DataInspector.DataInspector inspector, int count)
        {
            this.inspector = inspector;
            this.count = count;
        }

        public int FetchCount()
        {
            return count;
        }

        string ReplaceBreakLines(string input)
        {
            return input.Replace('\r', '.').Replace('\n', '.').Replace('\f', '.').Replace('\v', '.');
        }

        public IList<HexItem> FetchRange(long startIndex, long count)
        {
            System.Diagnostics.Trace.WriteLine("FetchRange: " + startIndex + "," + count);
            //Thread.Sleep(1000);

            long bytestart = startIndex *= 16;
            long bytelen = count * 16;

            inspector.Stream.Position = bytestart;
            byte[] buffer = inspector.Read((int)bytelen);

            IList<HexItem> output = new List<HexItem>();

            //StringBuilder value = new StringBuilder();

            int i = 0;
            long lineNumber = startIndex;

            char[] chars = new char[16];
            byte[] bytes = new byte[16];

            foreach (byte b in buffer)
            {
                chars[i] = Convert.ToChar(b);
                bytes[i] = b;

                if (i++ == 0x0F)
                {
                    output.Add(new HexItem() { LineNumber = lineNumber, AsciiData = chars, HexData = bytes });
                    lineNumber += 0x10;
                    //Array.Clear(chars, 0, chars.Length);
                    //Array.Clear(bytes, 0, bytes.Length);
                    chars = new char[16];
                    bytes = new byte[16];
                    i = 0;
                }
            }
            
            if (i > 0)
            {
                Array.Resize(ref chars, i);
                Array.Resize(ref bytes, i);
                output.Add(new HexItem() { LineNumber = lineNumber, AsciiData = chars, HexData = bytes });
            }

            return output;
        }
    }
}
